import React, { useState, useRef, useMemo } from "react";
import bem from '@/utils/bem';
import "@/components/goodsCard/goodsCard.scss";
import GoodsCard from "@/components/goodsCard/goodsCard";
import { getDataList } from '@/api/product';
import { InfiniteScroll } from 'antd-mobile';
import { convertDataList } from '@/utils/convert';
import { RequestData } from "@/components/table/typing";
import useFetchData from "@/components/table/useFetchData";
import Loadding from "@/components/loadding";

export interface ScrollGoodsProps {
    showType?: 'half-line' | 'full-line';
    url?: string;
    params?: {
        pageNum: number;
        pageSize: number;
        [key: string]: any;
    };
    columns?: any[];
    threshold?: number;
    debounceTime?: number;
}


const defaultProps = {
    showType: 'half-line',
    url: '/api/product/getRecommend',
    params: {
        pageNum: 1,
        pageSize: 10
    },
    threshold: 300,
    debounceTime: 600,
    columns: [
        {
            sourceKey: 'productId',
            dataIndex: 'id'
        },
        {
            sourceKey: 'productName',
            dataIndex: 'title'
        },
        {
            sourceKey: 'mainImage',
            dataIndex: 'imgUrl'
        },
        {
            sourceKey: 'salePrice',
            dataIndex: 'price'
        },
    ],
}

const scrollGoods: React.FC<ScrollGoodsProps> = (props) => {
    const {
        showType,
        columns,
        params,
        url,
        threshold,
        debounceTime,
        ...rest
    } = {
        ...defaultProps,
        ...props,
    }

    const b = bem('goods-card');
    const [hasMore, setHasMore] = useState(true)
    const [dataList, setDataList] = useState<Record<string, any>[]>([]);
    const [pageIndex, setPageIndex] = useState(params.pageNum);
    const isLoadingRef = useRef(false);


    // ============================ useFetchData ============================
    // Inside useMemo for getRecommendData
    const fetchList = useMemo(() => {
        return async (fetchParam?: { pageSize: number; current: number }) => {
            const actionParams = {
                ...params,
                pageNum: fetchParam?.current,
                pageSize: fetchParam?.pageSize,

            };
            const res = await getDataList(url, actionParams);
            const data = res.data?.list || [];
            const total = res.data?.totalCount || 0;
            return { data, total, success: true } as RequestData<any>;
        };
    }, [params]);


    const action = useFetchData(fetchList, [], {
        loading: false,
        manual: false,
        completeManual: true,
        pageInfo: {
            current: pageIndex,
            pageSize: params.pageSize,
        },
        postData: (data) => {
            return convertDataList(data, columns);
        },
        debounceTime,
    });

    const loadMore = async () => {
        if (isLoadingRef.current || !hasMore) {
            return;
        }

        isLoadingRef.current = true;

        const { data, total = 0 } = await action.completeManualRequest();
        const newData = data;
        console.log('newData', newData);
        // 更新推荐数据
        setDataList(prev => [...prev, ...newData]);
        // 计算是否还有更多数据
        const currentTotal = dataList.length + newData.length;

        const hasMoreData = currentTotal < total;
        setHasMore(hasMoreData);
        if (hasMoreData) {
            const newPageIndex = pageIndex + 1;
            setPageIndex(newPageIndex);

            // 修改pageInfo
            action.setPageInfo({
                current: newPageIndex,
            });
        }

        isLoadingRef.current = false;
    };

    return (
        <>
            <div className={b('box')}>
                {
                   
                    dataList?.map((item, index) => (
                        <GoodsCard key={`${index}-${item.id}`} href={`/goods/detail/${item.id}`} {...item} />
                    ))
                }
            </div>

            <div className="seal-goods-card-box__loading">
                <InfiniteScroll
                    loadMore={loadMore}
                    hasMore={hasMore}
                    threshold={threshold}>

                    {hasMore ? (
                        <Loadding visible={true} />
                    ) : (
                        <span>没有数据了……</span>
                    )}
                </InfiniteScroll>
            </div >
        </>
    );
};

export default scrollGoods;